package com.activity.common.jwt;

import com.activity.common.result.Result;
import com.activity.common.util.JwtUtil;
import com.activity.common.util.TokenVerify;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }



        String token = request.getHeader("token");

        if (token==null){
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().append(JSON.toJSONString(Result.fail("token empty",null)));
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //拿到在接口上使用TokenVerify子定义注解,设置的role
        TokenVerify annotation =(TokenVerify) method.getAnnotation(TokenVerify.class);
//        String role=annotation.role();
        //拿到jwt中的userlevel
        JwtUtil jwtUtil = new JwtUtil();
        JSONObject payload = jwtUtil.getPayload(token);

        if (method.isAnnotationPresent(TokenVerify.class)){
//            if (token == null || JwtUtil.verity(token)==false){
                if (JwtUtil.verity(token)==false){
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().append(JSON.toJSONString(Result.fail("token fail",null)));
                return false;
            }else {
                return true;
                //在这里拿到jwt中的userlevel和自定义注解中的角色做比较
//                if (role.equals(userLevel)|| userLevel.equals("4")){
//                    return true;
//                }else {
//                    response.getWriter().append(Result.fail("token success,but user leavel not enough",null).toString());
//                    return false;
//                }
            }
        }
        return true;
    }
   


}
